package com.easylinkin.linkappapi.openapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.easylinkin.linkappapi.alarm.entity.AlarmTemplate;
import com.easylinkin.linkappapi.alarm.mapper.AlarmTemplateMapper;
import com.easylinkin.linkappapi.intelligentrule.entity.IntelligentRuleExpression;
import com.easylinkin.linkappapi.intelligentrule.mapper.IntelligentRuleExpressionMapper;
import com.easylinkin.linkappapi.linkage.entity.LinkageConfigRefDownDevice;
import com.easylinkin.linkappapi.linkage.entity.LinkageConfigRelateServiceParm;
import com.easylinkin.linkappapi.linkage.mapper.LinkageConfigRefDownDeviceMapper;
import com.easylinkin.linkappapi.linkage.mapper.LinkageConfigRelateServiceParmMapper;
import com.easylinkin.linkappapi.openapi.service.ApplicationCopyDeviceService;
import com.easylinkin.linkappapi.ruleengine.entity.*;
import com.easylinkin.linkappapi.ruleengine.mapper.*;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.space.entity.LinkappArea;
import com.easylinkin.linkappapi.space.mapper.LinkappAreaMapper;
import com.easylinkin.linkappapi.taskscheduler.entity.JobEntity;
import com.easylinkin.linkappapi.taskscheduler.mapper.JobEntityMapper;
import com.easylinkin.linkappapi.taskscheduler.service.TaskSchedulerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: linkapp-group-cloud
 * @description: 规则引擎
 * @author: chenkaixuan
 * @create: 2021-09-07 17:27
 */
@Slf4j
@Service
public class ApplicationCopyDeviceRuleEngineServiceImpl implements ApplicationCopyDeviceService {
    @Resource
    RuleEngineMapper ruleEngineMapper;
    @Resource
    LinkappAreaMapper linkappAreaMapper;
    @Resource
    RuleTriggerMapper ruleTriggerMapper;
    @Resource
    RuleTriggerRefDeviceMapper ruleTriggerRefDeviceMapper;
    @Resource
    IntelligentRuleExpressionMapper intelligentRuleExpressionMapper;
    @Resource
    JobEntityMapper jobEntityMapper;
    @Resource
    TaskSchedulerService taskSchedulerService;
    @Resource
    RuleConditionMapper ruleConditionMapper;
    @Resource
    RuleExecutionMapper ruleExecutionMapper;
    @Resource
    AlarmTemplateMapper alarmTemplateMapper;
    @Resource
    LinkageConfigRelateServiceParmMapper linkageConfigRelateServiceParmMapper;
    @Resource
    LinkageConfigRefDownDeviceMapper linkageConfigRefDownDeviceMapper;

    @Override
    public RestMessage copy(HashMap<String, String> screenmap, HashMap<String, String> map, LinkappUser newLinkappUser, LinkappUser oldLinkappUser) {
        if (newLinkappUser == null || oldLinkappUser == null) {
            return RestBuilders.failureMessage().setMessage("用户为空");
        }
        RestMessage restMessage = RestBuilders.successBuilder().build();
        if (map == null || map.size() <= 0) {
            return restMessage;
        }
        RuleEngine ruleEngine = new RuleEngine();
        ruleEngine.setTenantId(oldLinkappUser.getTenantId());
        List<RuleEngine> ruleEngines = ruleEngineMapper.getRuleEngines(ruleEngine, null);
        if (ruleEngines == null || ruleEngines.size() <= 0) {
            return restMessage;
        }
        //保存规则引擎
        configRuleEngine(ruleEngines, newLinkappUser, map);
        log.info("规则引擎拷贝完成");
        return restMessage;
    }

    @Override
    public RestMessage copy(LinkappUser newLinkappUser, LinkappUser oldLinkappUser) {
        return null;
    }

    /***
     * 保存规则引擎
     * @param ruleEngines
     * @param newLinkappUser
     * @param map
     */
    private void configRuleEngine(List<RuleEngine> ruleEngines, LinkappUser newLinkappUser, HashMap<String, String> map) {
        if (ruleEngines == null || ruleEngines.size() <= 0) {
            return;
        }
        //获取所有的区域ID
        HashSet<String> areaIdSet = new HashSet<>();
        ruleEngines.stream().forEach(m -> {
            if (StringUtils.isEmpty(m.getAreaId())) {
                return;
            }
            if (!m.getAreaId().equals(m.getSpaceId())) {
                areaIdSet.add(m.getSpaceId());
            }
            areaIdSet.add(m.getAreaId());
        });
        //获取旧值
        LinkappArea linkappArea = new LinkappArea();
        linkappArea.setIds(areaIdSet);
        List<LinkappArea> linkappAreaList = linkappAreaMapper.selectLinkappAreaListAllGlobal(linkappArea);
        if (linkappAreaList == null || linkappAreaList.size() <= 0) {
            return;
        }
        //key id,value areaPath
        Map<String, String> oldAreaMap = linkappAreaList.stream().collect(Collectors.toMap(LinkappArea::getId, LinkappArea::getAreaPath, (m1, m2) -> m2));
        //获取新值
        linkappArea= new LinkappArea();
        linkappArea.setTenantId(newLinkappUser.getTenantId());
        linkappArea.setAreaPaths(new ArrayList<>(oldAreaMap.values()));
        linkappAreaList = linkappAreaMapper.selectLinkappAreaListAllGlobal(linkappArea);
        if (linkappAreaList == null || linkappAreaList.size() <= 0) {
            return;
        }
        //key areaPath, value id
        Map<String, String> newAreaMap = linkappAreaList.stream().collect(Collectors.toMap(LinkappArea::getAreaPath, LinkappArea::getId, (m1, m2) -> m2));
        Date date = new Date();
        //保存id关系映射
        HashMap<String, String> ruleEnginesIdsMap = new HashMap<>();
        //通过就区域id查找areaPath，在通过areapath查找新值id
        ruleEngines = ruleEngines.stream().map(m -> {
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            ruleEnginesIdsMap.put(m.getId(), id);
            m.setId(id);
            m.setTenantId(newLinkappUser.getTenantId());
            m.setCreateTime(date);
            m.setModifyTime(date);
            //默认停用
            m.setStatus(0);
            m.setCreator(newLinkappUser.getId() + "");
            m.setModifier(newLinkappUser.getId() + "");
            if (!StringUtils.isEmpty(m.getAreaId()) && oldAreaMap.get(m.getAreaId()) != null) {
                m.setSpaceId(newAreaMap.get(oldAreaMap.get(m.getSpaceId())));
                m.setAreaId(newAreaMap.get(oldAreaMap.get(m.getAreaId())));
            }
            return m;
        }).collect(Collectors.toList());
        int batchSize = 100;
        //保存规则引擎
        if (ruleEngines != null && ruleEngines.size() > 0) {
            for (int idx = 0; idx < ruleEngines.size(); idx += batchSize) {
                List<RuleEngine> list = ruleEngines.subList(idx, Math.min(ruleEngines.size(), idx + batchSize));
                ruleEngineMapper.batchInsert(list);
            }
        }
        //保存规则触发器
        saveRuleTriggers(ruleEnginesIdsMap, newLinkappUser, map);
        //保存规则条件器
        saveRuleCondition(ruleEnginesIdsMap, map);
        //保存规则执行器
        saveRuleExecution(ruleEnginesIdsMap, newLinkappUser, map);
    }


    /***
     * 保存规则触发器
     * @param ruleEnginesIdsMap key 旧值id,value 新值id
     */
    private void saveRuleTriggers(HashMap<String, String> ruleEnginesIdsMap, LinkappUser newLinkappUser, HashMap<String, String> deviceMap) {
        if (ruleEnginesIdsMap == null || ruleEnginesIdsMap.size() <= 0) {
            return;
        }
        RuleTrigger ruleTrigger = new RuleTrigger();
        ruleTrigger.setRuleEngineIds(ruleEnginesIdsMap.keySet());
        List<RuleTrigger> ruleTriggers = ruleTriggerMapper.getRuleTriggers(ruleTrigger);
        if (ruleTriggers == null || ruleTriggers.size() <= 0) {
            return;
        }
        int size = (int) (ruleTriggers.size() * 0.75) + 1;
        HashMap<String, String> ruleTriggerIdsMap = new HashMap<>(size);
        Set<String> jobEntityIdSet = ruleTriggers.stream().filter(m -> !StringUtils.isEmpty(m.getJobEntityId())).map(m -> m.getJobEntityId()).collect(Collectors.toSet());
        Date date = new Date();
        ruleTriggers = ruleTriggers.stream().map(m -> {
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            ruleTriggerIdsMap.put(m.getId(), id);
            m.setId(id);
            m.setCreateTime(date);
            m.setModifyTime(date);
            m.setRuleEngineId(ruleEnginesIdsMap.get(m.getRuleEngineId()));
            return m;
        }).collect(Collectors.toList());

        //组装定时器
        size = (int) (jobEntityIdSet.size() * 0.75) + 1;
        HashMap<String, String> jobEntityMapperMap = new HashMap<>(size);
        List<JobEntity> jobEntityList = configRuleTriggerJob(newLinkappUser, jobEntityIdSet, jobEntityMapperMap, ruleTriggerIdsMap);
        //将定时器ID组装触发器
        if (jobEntityMapperMap != null && jobEntityMapperMap.size() > 0) {
            ruleTriggers = ruleTriggers.stream().map(m -> {
                if (jobEntityMapperMap.get(m.getJobEntityId()) != null) {
                    m.setJobEntityId(jobEntityMapperMap.get(m.getJobEntityId()));
                }
                return m;
            }).collect(Collectors.toList());
        }
        //组装关联设备
        List<RuleTriggerRefDevice> ruleTriggerRefDevices = configRuleTriggerDevice(ruleTriggerIdsMap, deviceMap);
        //规则表达式
        List<IntelligentRuleExpression> intelligentRuleExpressions = configRuleTriggerExpression(ruleTriggerIdsMap);
        int batchSize = 100;
        //保存触发器
        if (ruleTriggers != null && ruleTriggers.size() > 0) {
            for (int idx = 0; idx < ruleTriggers.size(); idx += batchSize) {
                List<RuleTrigger> list = ruleTriggers.subList(idx, Math.min(ruleTriggers.size(), idx + batchSize));
                ruleTriggerMapper.batchInsert(list);
            }
        }
        //保存定时器
        if (jobEntityList != null && jobEntityList.size() > 0) {
            for (JobEntity jobEntity : jobEntityList) {
                taskSchedulerService.saveTask(jobEntity);
            }
        }
        //保存关联设备
        if (ruleTriggerRefDevices != null && ruleTriggerRefDevices.size() > 0) {
            for (int idx = 0; idx < ruleTriggerRefDevices.size(); idx += batchSize) {
                List<RuleTriggerRefDevice> list = ruleTriggerRefDevices.subList(idx, Math.min(ruleTriggerRefDevices.size(), idx + batchSize));
                ruleTriggerRefDeviceMapper.batchInsert(list);
            }
        }
        //保存规则表达式
        if (intelligentRuleExpressions != null && intelligentRuleExpressions.size() > 0) {
            for (int idx = 0; idx < intelligentRuleExpressions.size(); idx += batchSize) {
                List<IntelligentRuleExpression> list = intelligentRuleExpressions.subList(idx, Math.min(intelligentRuleExpressions.size(), idx + batchSize));
                intelligentRuleExpressionMapper.batchInsert(list);
            }
        }
    }


    /***
     * 保存规则条件器
     * @param ruleEnginesIdsMap
     * @param deviceMap
     */
    private void saveRuleCondition(HashMap<String, String> ruleEnginesIdsMap, HashMap<String, String> deviceMap) {
        if (ruleEnginesIdsMap == null || ruleEnginesIdsMap.size() <= 0) {
            return;
        }
        RuleCondition ruleCondition = new RuleCondition();
        ruleCondition.setRuleEngineIds(ruleEnginesIdsMap.keySet());
        List<RuleCondition> ruleConditions = ruleConditionMapper.getRuleConditions(ruleCondition);
        if (ruleConditions == null || ruleConditions.size() <= 0) {
            return;
        }
        Date date = new Date();
        int size = (int) (ruleConditions.size() * 0.75) + 1;
        HashMap<String, String> ruleConditionIdsMapperMap = new HashMap<>(size);
        ruleConditions = ruleConditions.stream().map(m -> {
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            ruleConditionIdsMapperMap.put(m.getId(), id);
            m.setId(id);
            m.setRuleEngineId(ruleEnginesIdsMap.get(m.getRuleEngineId()));
            m.setCreateTime(date);
            m.setModifyTime(date);
            if (!StringUtils.isEmpty(m.getDeviceCode())) {
                m.setDeviceCode(deviceMap.get(m.getDeviceCode()));
            }
            return m;
        }).collect(Collectors.toList());
        //组装规则表达式
        List<IntelligentRuleExpression> intelligentRuleExpressions = configRuleConditionExpression(ruleConditionIdsMapperMap);
        int batchSize = 100;
        //保存条件器
        if (ruleConditions != null && ruleConditions.size() > 0) {
            for (int idx = 0; idx < ruleConditions.size(); idx += batchSize) {
                List<RuleCondition> list = ruleConditions.subList(idx, Math.min(ruleConditions.size(), idx + batchSize));
                ruleConditionMapper.batchInsert(list);
            }
        }
        //保存规则表达式
        if (intelligentRuleExpressions != null && intelligentRuleExpressions.size() > 0) {
            for (int idx = 0; idx < intelligentRuleExpressions.size(); idx += batchSize) {
                List<IntelligentRuleExpression> list = intelligentRuleExpressions.subList(idx, Math.min(intelligentRuleExpressions.size(), idx + batchSize));
                intelligentRuleExpressionMapper.batchInsert(list);
            }
        }

    }

    /***
     * 保存规则执行器
     * @param ruleEnginesIdsMap
     * @param deviceMap
     */
    private void saveRuleExecution(HashMap<String, String> ruleEnginesIdsMap, LinkappUser newLinkappUser, HashMap<String, String> deviceMap) {
        if (ruleEnginesIdsMap == null || ruleEnginesIdsMap.size() <= 0) {
            return;
        }
        RuleExecution ruleExecution = new RuleExecution();
        ruleExecution.setRuleEngineIds(ruleEnginesIdsMap.keySet());
        List<RuleExecution> ruleExecutions = ruleExecutionMapper.getRuleExecutions(ruleExecution);
        if (ruleExecutions == null || ruleExecutions.size() <= 0) {
            return;
        }
        //获取告警模板映射关系
        Map<String, String> oldAlarmIdMap = null, newAlarmIdMap = null;
        Set<String> alarmTemplateIds = ruleExecutions.stream().filter(m -> !StringUtils.isEmpty(m.getAlarmTemplateId())).map(RuleExecution::getAlarmTemplateId).collect(Collectors.toSet());
        if (alarmTemplateIds != null && alarmTemplateIds.size() > 0) {
            //获取旧告警模板
            List<AlarmTemplate> alarmTemplateList = alarmTemplateMapper.selectBatchIds(alarmTemplateIds);
            //获取所有名称
            oldAlarmIdMap = alarmTemplateList.stream().collect(Collectors.toMap(AlarmTemplate::getId, AlarmTemplate::getName, (k1, k2) -> k2));
            AlarmTemplate alarmTemplate = new AlarmTemplate();
            alarmTemplate.setNames(new HashSet<>(oldAlarmIdMap.values()));
            alarmTemplate.setTenantId(newLinkappUser.getTenantId());
            //新告警模板
            alarmTemplateList = alarmTemplateMapper.getAlarmTemplates(alarmTemplate, newLinkappUser.getId() + "");
            newAlarmIdMap = alarmTemplateList.stream().collect(Collectors.toMap(AlarmTemplate::getName, AlarmTemplate::getId, (k1, k2) -> k2));
        }

        Date date = new Date();
        Map<String, String> finalOldAlarmIdMap = oldAlarmIdMap;
        Map<String, String> finalNewAlarmIdMap = newAlarmIdMap;
        int size = (int) (ruleExecutions.size() * 0.75) + 1;
        HashMap<String, String> ruleExecutionIdsMapperMap = new HashMap<>(size);
        ruleExecutions = ruleExecutions.stream().map(m -> {
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            ruleExecutionIdsMapperMap.put(m.getId(), id);
            m.setId(id);
            m.setRuleEngineId(ruleEnginesIdsMap.get(m.getRuleEngineId()));
            m.setCreateTime(date);
            m.setModifyTime(date);
            if (!StringUtils.isEmpty(m.getAlarmTemplateId()) && finalOldAlarmIdMap != null && finalNewAlarmIdMap != null
                    && finalOldAlarmIdMap.get(m.getAlarmTemplateId()) != null) {
                m.setAlarmTemplateId(finalNewAlarmIdMap.get(finalOldAlarmIdMap.get(m.getAlarmTemplateId())));
            }
            return m;
        }).collect(Collectors.toList());
        //组装下行参数
        List<LinkageConfigRelateServiceParm> linkageConfigRelateServiceParms = configRuleExecutionServiceParm(ruleExecutionIdsMapperMap);
        //组装下行设备
        List<LinkageConfigRefDownDevice> linkageConfigRefDownDevices = configRuleExecutionServiceDevice(ruleExecutionIdsMapperMap, deviceMap);
        int batchSize = 100;
        //保存执行器
        if (ruleExecutions != null && ruleExecutions.size() > 0) {
            for (int idx = 0; idx < ruleExecutions.size(); idx += batchSize) {
                List<RuleExecution> list = ruleExecutions.subList(idx, Math.min(ruleExecutions.size(), idx + batchSize));
                ruleExecutionMapper.batchInsert(list);
            }
        }
        //保存下行参数
        if (linkageConfigRelateServiceParms != null && linkageConfigRelateServiceParms.size() > 0) {
            for (int idx = 0; idx < linkageConfigRelateServiceParms.size(); idx += batchSize) {
                List<LinkageConfigRelateServiceParm> list = linkageConfigRelateServiceParms.subList(idx, Math.min(linkageConfigRelateServiceParms.size(), idx + batchSize));
                linkageConfigRelateServiceParmMapper.batchInsert(list);
            }
        }
        //保存下行设备
        if (linkageConfigRefDownDevices != null && linkageConfigRefDownDevices.size() > 0) {
            for (int idx = 0; idx < linkageConfigRefDownDevices.size(); idx += batchSize) {
                List<LinkageConfigRefDownDevice> list = linkageConfigRefDownDevices.subList(idx, Math.min(linkageConfigRefDownDevices.size(), idx + batchSize));
                linkageConfigRefDownDeviceMapper.batchInsert(list);
            }
        }
    }

    /**
     * 组装触发器-关联设备
     */
    private List<RuleTriggerRefDevice> configRuleTriggerDevice(HashMap<String, String> ruleTriggerIdsMap, HashMap<String, String> deviceMap) {
        if (ruleTriggerIdsMap == null || ruleTriggerIdsMap.size() <= 0) {
            return null;
        }
        //查询所有关联设备
        List<RuleTriggerRefDevice> ruleTriggerRefDeviceList = new LambdaQueryChainWrapper<>(ruleTriggerRefDeviceMapper)
                .in(RuleTriggerRefDevice::getRuleTriggerId, ruleTriggerIdsMap.keySet())
                .list();
        if (ruleTriggerRefDeviceList == null || ruleTriggerRefDeviceList.size() <= 0) {
            return null;
        }
        //替换设备,替换ruleTriggerId
        ruleTriggerRefDeviceList = ruleTriggerRefDeviceList.stream().map(m -> {
            m.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            m.setRuleTriggerId(ruleTriggerIdsMap.get(m.getRuleTriggerId()));
            m.setDeviceCode(deviceMap.get(m.getDeviceCode()));
            return m;
        }).collect(Collectors.toList());
        return ruleTriggerRefDeviceList;
    }

    /***
     *  组装触发器-规则表达式
     */
    private List<IntelligentRuleExpression> configRuleTriggerExpression(HashMap<String, String> ruleTriggerIdsMap) {
        if (ruleTriggerIdsMap == null || ruleTriggerIdsMap.size() <= 0) {
            return null;
        }
        //查询所有关联规则
        QueryWrapper<IntelligentRuleExpression> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("rule_trigger_id", ruleTriggerIdsMap.keySet());
        queryWrapper.eq("delete_state", 1);
        List<IntelligentRuleExpression> intelligentRuleExpressions = intelligentRuleExpressionMapper.selectList(queryWrapper);
        if (intelligentRuleExpressions == null || intelligentRuleExpressions.size() <= 0) {
            return null;
        }
        intelligentRuleExpressions = intelligentRuleExpressions.stream().map(m -> {
            m.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            m.setRuleTriggerId(ruleTriggerIdsMap.get(m.getRuleTriggerId()));
            return m;
        }).collect(Collectors.toList());
        return intelligentRuleExpressions;
    }

    /***
     * 组装触发器-定时器
     * @param newLinkappUser
     * @param jobEntityIdSet
     * @param ruleTriggerJobMapperMap
     * @param ruleTriggerIdsMap
     * @return
     */
    private List<JobEntity> configRuleTriggerJob(LinkappUser newLinkappUser, Set<String> jobEntityIdSet, HashMap<String, String> ruleTriggerJobMapperMap, HashMap<String, String> ruleTriggerIdsMap) {
        if (jobEntityIdSet == null || jobEntityIdSet.size() <= 0) {
            return null;
        }
        //获取所有定时器
        List<JobEntity> jobEntityList = new LambdaQueryChainWrapper<>(jobEntityMapper)
                .in(JobEntity::getId, jobEntityIdSet)
                .list();
        if (jobEntityList == null || jobEntityList.size() <= 0) {
            return null;
        }
        Date date = new Date();
        String separator = "_";
        jobEntityList = jobEntityList.stream().map(m -> {
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            ruleTriggerJobMapperMap.put(m.getId(), id);
            m.setId(id);
            //之前是存储的触发器ID，这里获取新ID存入，jobEntity.setJobName(ruleTrigger.getId());
            m.setJobName(ruleTriggerIdsMap.get(m.getJobName()));
            //替换"_"符号之后的租户ID
            if (!StringUtils.isEmpty(m.getJobGroup()) && m.getJobGroup().indexOf(separator) != -1) {
                String[] split = m.getJobGroup().split(separator);
                m.setJobGroup(split[0] + separator + newLinkappUser.getTenantId());
            } else {
                m.setJobGroup(newLinkappUser.getTenantId());
            }
            //默认禁用
            m.setJobStatus("0");
            m.setModifyTime(date);
            m.setCreateTime(date);
            return m;
        }).collect(Collectors.toList());
        return jobEntityList;
    }


    /***
     * 组装条件器-规则表达式
     * @param ruleConditionIdsMapperMap
     */
    private List<IntelligentRuleExpression> configRuleConditionExpression(HashMap<String, String> ruleConditionIdsMapperMap) {
        if (ruleConditionIdsMapperMap == null || ruleConditionIdsMapperMap.size() <= 0) {
            return null;
        }
        //查询所有关联规则
        QueryWrapper<IntelligentRuleExpression> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("rule_condition_id", ruleConditionIdsMapperMap.keySet());
        queryWrapper.eq("delete_state", 1);
        List<IntelligentRuleExpression> intelligentRuleExpressions = intelligentRuleExpressionMapper.selectList(queryWrapper);
        if (intelligentRuleExpressions == null || intelligentRuleExpressions.size() <= 0) {
            return null;
        }
        intelligentRuleExpressions = intelligentRuleExpressions.stream().map(m -> {
            m.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            m.setRuleConditionId(ruleConditionIdsMapperMap.get(m.getRuleConditionId()));
            return m;
        }).collect(Collectors.toList());
        return intelligentRuleExpressions;
    }

    /***
     *  组装执行器-下行参数
     * @param ruleExecutionIdsMapperMap
     * @return
     */
    private List<LinkageConfigRelateServiceParm> configRuleExecutionServiceParm(HashMap<String, String> ruleExecutionIdsMapperMap) {
        if (ruleExecutionIdsMapperMap == null || ruleExecutionIdsMapperMap.size() <= 0) {
            return null;
        }
        List<LinkageConfigRelateServiceParm> serviceParmList = new LambdaQueryChainWrapper<>(linkageConfigRelateServiceParmMapper)
                .in(LinkageConfigRelateServiceParm::getRuleExecutionId, ruleExecutionIdsMapperMap.keySet())
                .list();
        if (serviceParmList == null || serviceParmList.size() <= 0) {
            return null;
        }
        HashMap<String, String> fatherSonMapperMap = new HashMap<>();
        serviceParmList = serviceParmList.stream().map(m -> {
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            fatherSonMapperMap.put(m.getId(), id);
            m.setId(id);
            m.setRuleExecutionId(ruleExecutionIdsMapperMap.get(m.getRuleExecutionId()));
            return m;
        }).map(m -> {
            if (!StringUtils.isEmpty(m.getParentId())) {
                m.setParentId(ruleExecutionIdsMapperMap.get(m.getParentId()));
            }
            return m;
        }).collect(Collectors.toList());
        return serviceParmList;
    }

    /***
     * 规则执行器-配置下行设备
     * @param ruleExecutionIdsMapperMap 执行器映射
     * @param deviceMap 设备映射
     * @return
     */
    private List<LinkageConfigRefDownDevice> configRuleExecutionServiceDevice(HashMap<String, String> ruleExecutionIdsMapperMap, HashMap<String, String> deviceMap) {
        if (ruleExecutionIdsMapperMap == null || ruleExecutionIdsMapperMap.size() <= 0) {
            return null;
        }
        List<LinkageConfigRefDownDevice> configRefDownDevices = new LambdaQueryChainWrapper<>(linkageConfigRefDownDeviceMapper)
                .in(LinkageConfigRefDownDevice::getRuleExecutionId, ruleExecutionIdsMapperMap.keySet())
                .list();
        if (configRefDownDevices == null || configRefDownDevices.size() <= 0) {
            return null;
        }
        configRefDownDevices = configRefDownDevices.stream().map(m -> {
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            m.setId(id);
            m.setRuleExecutionId(ruleExecutionIdsMapperMap.get(m.getRuleExecutionId()));
            m.setDeviceCode(deviceMap.get(m.getDeviceCode()));
            return m;
        }).collect(Collectors.toList());
        return configRefDownDevices;
    }
}
